# coding=utf-8
'''
author:董新强
createdate:
description:
'''
import os
import time
import traceback
from contextlib import contextmanager

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

import setting

DbEngine = create_engine(setting.MYSQL_DB_CONN_STR, echo=False, pool_size=50, pool_recycle=3600)


class DbSession:

    @classmethod
    @contextmanager
    def create(cls):

        exception, st = None, time.time()
        cl_session = scoped_session(sessionmaker(DbEngine))

        session = cl_session()
        try:
            yield session
            session.commit()
        except Exception as e:
            exception = e

            try:
                session.rollback()
            except Exception as e:
                print(e)
        finally:
            if cl_session is not None:
                cl_session.remove()

        # -----------------------监控数据库时间--------------------------------------------------------------
        if setting.MONITOR_DB_ACCESS_TIME:  # 如果需要监控数据库范围时间
            try:
                span = time.time() - st
                if span > 1:  # 如果执行时间超过1秒,就进行记录
                    stack = traceback.extract_stack()[-3]
                    info = '文件=>' + str(os.path.basename(stack[0])) + '   方法=>' + str(stack[2])
                    print('DB访问耗时监控', info, ' 耗时(秒)=>' + str(round(span, 2)), 9)
            except:
                pass

        # ----------重新抛出异常----------
        if exception:
            raise exception
